import { mapMutations, mapActions, mapState } from "vuex";
import _ from "lodash";
import { typeClassName } from "@/pages/config/classNameMap";
const requireComponent = require.context("./", true, /[A-Z]\w+\.(vue)$/);
const comp = {};
requireComponent.keys().forEach((fileName) => {
  if (fileName != "./index.vue") {
    const componentConfig = requireComponent(fileName);
    const name = componentConfig.default.name;
    const componentName = _.upperFirst(
      _.camelCase(
        name
          .split("/")
          .pop()
          .replace(/\.\w+$/, "")
      )
    );
    comp[componentName] = componentConfig.default || componentConfig;
  }
});
Object.keys(comp).map((key) => {
  comp[key].components = comp;
});
export default {
  components: comp,
  data() {
    return {
      vms: {}, //页面组件vue实例
      models: {
        //模型
        accountPeriod: {
          ...typeClassName["accountPeriod"],
        },
        reductionWorkUnit: {
          ...typeClassName["reductionWorkUnit"],
        },
        reductionWorkCenter: {
          ...typeClassName["reductionWorkCenter"],
        },
        workReportRecord: {
          ...typeClassName["workReportRecord"],
        },
        workNotice: {
          ...typeClassName["workNotice"],
        },
      },
      onlyRead: false,
      equipTypeOptions: [],
      productOptions: [],
      workNoticeId: null,
      productId: "",
      productStatus:"",
      dataSet: {
        //数据集
        tableData: [],
        workTableData: [],
        formData: {},
        workReport: {},
        workUnitData: {},
      },
      hierOptions: [],
      locationOptions: [],
    };
  },
  provide() {
    return {
      anc: this,
    };
  },
  computed: {
    // filterEquipTypeOptions() {
    //   return this.equipTypeOptions.filter((d) => d.category === "1");
    // },
  },
  watch: {},
  created() {
    Object.keys(this.models).map((k) => {
      this.models[k].clz = this.$modelObject.create(this.models[k].modelType);
      this.models[k].clzs = this.$modelObject.create(
        this.models[k].modelType + "Collection"
      );
    });
  },
  mounted() {
    this.$nextTick(() => {
      this.getProduct();
      if (process.env.NODE_ENV === "development") {
        console.log(this);
      }
    });
  },
  methods: {
    /**
     *
     * @param {分页} pageNavigation
     * @param {筛选条件} filter
     * @param {*} orderBy
     * 页面加载方法
     */
    loadPage() {
      let data = {
        type: this.models["reductionWorkUnit"].type,
        className: this.models["reductionWorkUnit"].className,
      };

      let fileStr = this._$setFilteStr(data);
      let newFilter = {
        condition: fileStr,
      };

      this.$api.TwinsInstance.queryByPage(1, 10, newFilter).then((res) => {
        let workCenterId = res.records[0].values.workCenterId;
        this.workNoticeId = res.records[0].values.workNoticeId;
        this.dataSet.workUnitData = res.records[0];
        if (workCenterId == null) {
          this.$Message.info("该工位没有运行的工单");
          this.dataSet.tableData = [];
          return;
        }
        this.getWorkCenter(workCenterId);
      });
    },
    workLoadPage() {
      if (this.workNoticeId == null || this.workNoticeId == "") {
        this.$Message.info("没有工单")
        return
      }
      this._$queryByIds(this.models.workNotice.clzs, [this.workNoticeId]).then((flag) => {
        if (flag) {
          this.dataSet.workTableData =
            this.models.workNotice.clzs.valueRecords;
        }
      });
    },
    getWorkCenter(workCenterId) {
      this._$queryByIds(this.models.reductionWorkCenter.clzs, [
        workCenterId,
      ]).then((flag) => {
        let data = this.models.reductionWorkCenter.clzs.records[0];
        this.productId = data.values.productId
        this.productStatus = data.values.status
        let parentId = this._$getHierItemField(
          data.hier,
          "OutputRecords",
          "nodeId"
        );
        let tableData = data.hier.content.filter(
          (item) => item.parentId == parentId
        );

        let linkId = tableData.map((item) => {
          return item.link.linkId;
        });
        this.getWorkReport(linkId);
      });
    },
    getWorkReport(linkId) {
      if (linkId.length == 0) {
        this.dataSet.tableData = [];
        return;
      }
      this._$queryByIds(this.models.workReportRecord.clzs, linkId).then(
        (flag) => {
          this.dataSet.tableData =
            this.models.workReportRecord.clzs.records.map((item) => {
              return {
                ...item,
                ...item.values,
              };
            });
        }
      );
    },
    /**
     * 人员管理新增
     */
    handleCreate() {
      this.vms.createModal.show = true;
      this._modalShow("createModal");
      this.onlyRead = false;
      this.dataSet.formData = this.$modelObject.getTpl(
        this.models.accountPeriod.modelType
      ); // 这是一个整理接口数据JSON格式的方法
      this.dataSet.formData.values.productId = this.productId
      // this.dataSet.formData.values.endStatus = this.productStatus
    },
    /**
     *
     * @param {*} row
     * 人员管理查看
     */
    handleDetail(row) {
      this._modalShow("detailModal");
      this.dataSet.formData = row;
      this.onlyRead = true;
    },
    /**
     *
     * @param {*} row
     * 人员管理编辑
     */
    handleEdit(row) {
      this._modalShow("editModal");
      this.dataSet.formData = row;
    },
    /**
     *
     * @param {行数据} row
     * @param {索引} index
     * 人员管理删除数据
     */
    handleDelete(row, index) {
      console.log(row);
      this._$deleteConfirm(() => {
        let data = {
          workReport: row,
          workUnit: {
            ...this.dataSet.workUnitData,
          },
        };
        this.$api.production.deleteWorkReportRecord(data).then((res) => {
          this.vms.mainTable.pageNavigation.pageNavigation = 1;
          this.loadPage(this.vms.mainTable.pageNavigation, {});
        });
      });
    },
    /**
     *
     * @param {行数据} selection
     */

    // 创建人员管理提交
    createModalOk(btn) {
      // this.vms.createView.validate((valid) => {
      this._$validateAll([this.vms.createView], (valid) => {
        if (valid) {
          this._merge(this.dataSet.formData, {
            className: this.models.workReportRecord.className,
            type: this.models.workReportRecord.type,
          });
          let data = {
            workReport: {
              className: this.dataSet.formData.className,
              type: this.dataSet.formData.type,
              values: {
                ...this.dataSet.formData.values,
              },
            },
            workUnit: {
              ...this.dataSet.workUnitData,
            },
          };
          this.$api.production.addWorkReportRecord(data).then((res) => {
            this.vms.createModal.show = false;
            this._modalClose("createModal");
            btn.loading = false;
            this.vms.mainTable.pageNavigation.pageNavigation = 1;
            this.loadPage(this.vms.mainTable.pageNavigation, {});
          });
        } else {
          btn.loading = false;
          this.$Message.info("请填写必填内容");
        }
      });
    },
    editModalOk(btn) {
      this._$validateAll([this.vms.editView], (valid) => {
        this.models.workReportRecord.clz.setRecord(this.dataSet.formData);
        this.models.workReportRecord.clz.updateById().then((res) => {
          this.$Message.success("修改成功");
          this.vms.editModal.show = false;
          this._modalClose("editModal");
          btn.loading = false;
          this.loadPage();
        });
        btn.loading = false;
      });
    },
    submitWorkReportRecord(row) {
      row.values.status = "提交";
      this._merge(row, {
        className: this.models.workReportRecord.className,
        type: this.models.workReportRecord.type,
      });
      let data = {
        workReport: {
          className: row.className,
          type: row.type,
          id: row.id,
          values: {
            ...row.values,
          },
        },
        workUnit: {
          ...this.dataSet.workUnitData,
        },
      };
      this.$api.production.submitWorkReportRecord(data).then((res) => {
        this.$Message.success("提交成功");
        this.loadPage();
      });
    },
    getProduct() {
      let data = {
        type: "material",
        className: "MaterialDetail",
      };
      this.$api.ResourceInstance.query(data)
        .then((res) => {
          console.log(res);
          // this.dataSet.routing = res.data.data.records;
          this._$getOptions(res, "productOptions");
        })
        .catch((err) => {
          console.log(err);
        });
    },
    
  },
};
